package com.example.mytayunapi.Controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.example.mytayunapi.Config.AliPayConfig;
import com.example.mytayunapi.Entity.ordersInfo;
import com.example.mytayunapi.Mapper.ordersMapper;
import com.example.mytayunapi.Service.ordersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    private ordersService ordersservice;

    @Resource
    AliPayConfig aliPayConfig;


    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    @GetMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(@ModelAttribute AliPay alipay, HttpServletResponse httpResponse) throws Exception {
        //查询订单信息



        //创建Client,负责调用支付宝的API固定写法
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        //创建Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",alipay.getTraceNo());//我们自己的订单编号
        bizContent.put("total_amount",alipay.getTotalAmount());//交易的总金额
        bizContent.put("subject",alipay.getSubject());//购买的商品名称
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");//固定配置
        request.setBizContent(bizContent.toString());
//        request.setReturnUrl("http://localhost:63342/tayun-tayun/tayun-user-end/html/shop-buying.html");//支付完成后自动跳转到的页面
        //执行请求，拿到相应的结果,返回给浏览器
        // 支付宝支付完成后的回调URL，这里应该设置为RedirectController中的映射地址
        request.setReturnUrl("http://localhost:8080/alipay/return");

        //支付宝自己提供的页面
        String form = "";

        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

//    @GetMapping("/return")
//    public String handlePaymentReturn(HttpServletRequest request) {
//        // 这里可以添加一些日志记录，记录用户已经到达这个端点
//
//        // 构造重定向URL，使用完整URL，包括协议、主机名、端口和路径
//        String redirectUrl = "http://localhost:63342/tayun-tayun/tayun-user-end/html/shop-buying.html";
//
//        // 直接重定向到前端页面
//        return "redirect:" + redirectUrl;
//    }


    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }


            Integer tradeNo = Integer.valueOf(params.get("out_trade_no"));//订单编号
            Timestamp gmtPayment = Timestamp.valueOf(params.get("gmt_payment"));//支付时间
            String alipayTradeNo = params.get("trade_no");//支付宝交易编号

            String sign = params.get("sign"); // 支付宝通知中的签名
            String content = AlipaySignature.getSignCheckContentV1(params); // 获取待签名的内容，除去"sign"和"sign_type"
            // 调用验签方法，确保signType是正确的加密类型
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(),"UTF-8");
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));


                //查询订单
               ordersInfo orders = ordersservice.SelectedByOrder_id(tradeNo);

               if(orders!=null) {
                   orders.setOrder_status("已支付");
                   orders.setAlipayTradeNo(alipayTradeNo);
                   orders.setGmt_payment(gmtPayment);
                   ordersservice.updateById(orders);
               }
            }
        }
        return "success";
    }
}

